import time
from twisted.internet import reactor
import printfuncs as pf
from common.packets import PacketHandler

class PServer:
    loop_time = 0.05
    running = False
    last_time = 0
    network = None
    killed = None
        
    def setupNetwork(self, port=4886):
        from psnetwork import PServerNet
        network = PServerNet(port)
        reactor.addSystemEventTrigger('before', 'shutdown', self.reactorShutdown)
        reactor.callWhenRunning(self.reactorStartup)
        
    def reactorStartup(self):
        print "Reactor is a go!"
        
        self.running = True
        reactor.callInThread(self.mainLoop)
    
    def reactorShutdown(self):
        print "Reactor shutdown!"
        self.running = False
        
    def kill(self, time=0):
        if time > 0:
            self.killed = reactor.callLater(time, self.kill)
            return
        
        reactor.stop()
        
        
    def mainLoop(self):
        print "Main loop is running..."
        last_time = time.time()
        delta = 0.0
        while self.running:
            
            #---------------------------------------------------------------------------
            # DONE WITH MAIN LOOP
            # on with the timing code... Don't put anything after this
            #---------------------------------------------------------------------------
            
            #calculate internal timing delta
            #this determines how long the last iteration of the main loop lasted, and we can wait an appropriate amount.
            
            delta = time.time() - last_time
            
            timer = self.loop_time - delta
            if timer > 0:
                time.sleep(timer)
            
            #now calculate the overall timing of the last iteration so we know how much to adjust by for the next iteration.
            delta = time.time() - last_time
            last_time = time.time()
            
            
        print "Main loop ended."
            
server = PServer()
